package com.zkrt.upms.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.MD5;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.zkrt.upms.dto.TokenDTO;
import com.zkrt.upms.entity.TokenB;
import com.zkrt.upms.mapper.TokenBMapper;
import com.zkrt.upms.service.ITokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Base64;
import java.util.Date;

@Slf4j
@Service
public class TokenServiceImpl implements ITokenService {

    @Autowired
    private TokenBMapper tokenMapper;

    private final String identity = "Administrator@Zkrt";

    private final String token_prefix = "Zkrt@%s";

    /**
     * 初始化鉴权
     */
    @Override
    public void initialization() {
        final String decodeToken = String.format(token_prefix, System.currentTimeMillis());
        TokenDTO dto = new TokenDTO();
        dto.setIdentity(identity);
        dto.setToken(new String(Base64.getEncoder().encode(decodeToken.getBytes())));
        dto.setIsSuper(true);
        String payload = JSONObject.toJSONString(dto);
        LambdaQueryWrapper<TokenB> tokenWrapper = new LambdaQueryWrapper<>();
        tokenWrapper.eq(TokenB::getIdentifier, identity);
        tokenWrapper.last("limit 1");
        TokenB token = tokenMapper.selectOne(tokenWrapper);
        if (token == null) {
            token = new TokenB();
        }
        token.setIdentifier(identity);
        token.setToken(MD5.create().digestHex(payload).toUpperCase());
        int ident = 0;
        if (ObjectUtil.isNotEmpty(token.getId())) { // 更新token
            token.setUpdateTime(new Date(System.currentTimeMillis()));
            ident = tokenMapper.updateById(token);
        } else { // 新增Token
            token.setCreateTime(new Date(System.currentTimeMillis()));
            ident = tokenMapper.insert(token);
        }
        if (ident > 0) {
            log.info("[鉴权初始化完成] -> {}", identity);
        }
    }

    /**
     * 鉴权验证
     * @param authorization
     * @return
     */
    @Override
    public String verify(String authorization) {
        if (authorization == null) {
            return "token不能为空";
        }
        if (ObjectUtil.isNotEmpty(authorization)) {
            LambdaQueryWrapper<TokenB> tokenWrapper = new LambdaQueryWrapper<>();
            tokenWrapper.eq(TokenB::getToken, authorization);
            tokenWrapper.last("limit 1");
            TokenB token = tokenMapper.selectOne(tokenWrapper);
            if (token != null) {
                return null;
            }
        }
        return "鉴权失败";
    }

    /**
     * 获取鉴权信息
     * @param identity
     * @return
     */
    @Override
    public R get(String identity) {
        if (identity == null) {
            return R.failed("identity不能为空");
        }
        LambdaQueryWrapper<TokenB> tokenWrapper = new LambdaQueryWrapper<>();
        tokenWrapper.eq(TokenB::getIdentifier, identity);
        tokenWrapper.last("limit 1");
        TokenB token = tokenMapper.selectOne(tokenWrapper);
        if (token != null) {
            return R.ok(token);
        }
        return R.failed("获取鉴权失败");
    }

}
